package com.eptok.weixin.action;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.eptok.weixin.util.WxCooikeManager;

import hikefa.core.remote.client.RemoteCall;
import hikefa.core.remote.client.hessian3.MyHessianProxyFactory;
import oracle.sql.DATE;
import yspay.express.bean.Result;
import yspay.express.store.MsgConstat;
import yspay.express.util.CommonUtil;
import yspos.cpfs.enumeration.ExpInfoStatus;
import yspos.cpfs.enumeration.ExpSendMsgFuncState;
import yspos.cpfs.enumeration.ExpUserType;
import yspos.cpfs.express.entity.ExpExpressInfo;
import yspos.cpfs.express.entity.ExpUserinfo;
import yspos.cpfs.express.entity.ExpWebchatUserinfo;
import yspos.cpfs.remoteserver.iface.IExpressService;
import yspos.remoteserver.iface.IYsServer;

@Controller
@RequestMapping("/weixin")
public class IndexController  extends BaseDispatchAction{
	
	private static final Logger log = Logger.getLogger(IndexController.class);
	private IExpressService expressServer = (IExpressService) RemoteCall.getRemoteObject(IExpressService.class);
	private IYsServer ysServer = (IYsServer) RemoteCall.getRemoteObject(IYsServer.class);
	private static String lastVV = null;
	
	@RequestMapping(value = { "/index.do" })    
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) 
	{
		Long s = new Date().getTime();
		request.setAttribute("user", WxCooikeManager.getUser(request));
		request.setAttribute("wxUser", WxCooikeManager.getWxUser(request));
		log.info(new Date().getTime() - s);
		return new ModelAndView(PATH+"/index");
	}
	
	/*
	 * 跳转至用户登陆
	 */
	@RequestMapping(value = { "/indexUser.do" })    
	public ModelAndView indexUser(HttpServletRequest request, HttpServletResponse response) 
	{
		request.setAttribute("user", WxCooikeManager.getUser(request));
		request.setAttribute("wxUser", WxCooikeManager.getWxUser(request));
		return new ModelAndView(PATH+"/indexUser");
	}
	
	
	/*
	 * 跳转至用户登陆
	 */
	@RequestMapping(value = { "/indexKdy.do" })    
	public ModelAndView indexKdy(HttpServletRequest request, HttpServletResponse response) 
	{
		request.setAttribute("user", WxCooikeManager.getUser(request));
		request.setAttribute("wxUser", WxCooikeManager.getWxUser(request));
		return new ModelAndView(PATH+"/indexKdy");
	}
	
	/*
	 * 跳转至用户登陆
	 */
	@RequestMapping(value = { "/toReg.do" })    
	public ModelAndView doReg(HttpServletRequest request, HttpServletResponse response,
			String state,String code) 
	{
		request.setAttribute("user", WxCooikeManager.getUser(request));
		return new ModelAndView(PATH+"/user/reg");
	}
	
	@RequestMapping(value = { "/reg.do" })   
	public ModelAndView reg(HttpServletRequest request, HttpServletResponse response,
			ExpUserinfo info,String vv) 
	{
		try {
			if(vv== null || vv.equals(lastVV))
			{
				return toFail(request, "1", "参数异常或者请求重复");
			}
			lastVV = vv;
			//先判断该openid是否已经注册
			ExpWebchatUserinfo wxUser = WxCooikeManager.getWxUser(request);
			ExpUserinfo checkUser = expressServer.userinfoGetByopid(wxUser.getOpenId());
			if(null !=checkUser )
			{
				return toFail(request,"1", "该微信用户已经注册，不能再次注册");
			}
			
			info.setType(ExpUserType.NOML_USER.value);
			info.setOpenId(wxUser.getOpenId());
			Result ret = expressServer.userInfoReg(info);
			if(ret.isOk())
			{
				ExpUserinfo user = expressServer.userInfoFindByPhone(info.getPhone());
				WxCooikeManager.setUser(response, user);
				return toSuccess(request,ret.getCode(), ret.getMsg());
			}else
			{
				return toFail(request,ret.getCode(), ret.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return toFail(request,"1", "注册失败：系统错误");
		}
	}
	
	/*
	 * funcCode 定义：
	 * 1001：注册验证码
	 * 1002：解绑旧手机验证码
	 * 1003：绑定新手机验证码
	 * 发送验证码
	 */
	@RequestMapping(value = { "/sendCodeReg.do" })    
	@ResponseBody
	public Result sendCodeReg(HttpServletRequest request, HttpServletResponse response,String phone)
	{
		try {
			if(!CommonUtil.isMobile(phone))
			{
				return Result.init("1","请填写正确的手机号");
			}else
			{
				String code = MsgConstat.getCheckCode(4);
				String msg = "";
				ExpUserinfo user = expressServer.userInfoFindByPhone(phone);
				if(null != user)
				{
					return Result.init("1","该手机已经注册");
				}
				msg = MsgConstat.regCheckMsg.replace("{x}", ",");
				msg = msg.replace("{xxxxxxxxxxxxxxxxxxxxx}","["+code+"]");
				ysServer.sendMsg(ExpSendMsgFuncState.FUNC_SEND_REG.value, phone, code,msg);
				log.info("手机号："+phone+"，验证码："+code);
				return Result.init("0","验证码已发送");
			}
			
		} catch (Exception e) {
			log.error("发送验证码失败："+e.getMessage());
			return Result.init("1","验证码发送失败！");
		}
	}
	
	/*
	 * funcCode 定义：
	 * 1001：注册验证码
	 * 1002：解绑旧手机验证码
	 * 1003：绑定新手机验证码
	 * 发送验证码
	 */
	@RequestMapping(value = { "/sendCodeUnbindOld.do" })    
	@ResponseBody
	public Result sendCodeUnbindOld(HttpServletRequest request, HttpServletResponse response)
	{
		try {
			String phone = WxCooikeManager.getUser(request).getPhone();
			String code = MsgConstat.getCheckCode(4);
			String msg = "";
			msg = MsgConstat.unbindPhone.replace("{x}", ",");
			msg = msg.replace("{xxxxxxxxxxxxxxxxxxxxx}","["+code+"]");
			ysServer.sendMsg(ExpSendMsgFuncState.FUNC_SEND_UNBINDOLD.value, phone, code,msg);
			log.info("手机号："+phone+"，验证码："+code);
			return Result.init("0","验证码已发送");
		} catch (Exception e) {
			log.error("发送验证码失败："+e.getMessage());
			return Result.init("1","验证码发送失败！");
		}
	}
	
	/*
	 * funcCode 定义：
	 * 1001：注册验证码
	 * 1002：解绑旧手机验证码
	 * 1003：绑定新手机验证码
	 * 发送验证码 绑定新手机
	 */
	@RequestMapping(value = { "/sendCodeBindNew.do" })    
	@ResponseBody
	public Result sendCodeBindNew(HttpServletRequest request, HttpServletResponse response,String phone)
	{
		try {
			if(!CommonUtil.isMobile(phone))
			{
				return Result.init("1","请填写正确的手机号");
			}else
			{
				ExpUserinfo user = expressServer.userInfoFindByPhone(phone);
				if(null != user)
				{
					return Result.init("1","该手机已经绑定");
				}
				String code = MsgConstat.getCheckCode(4);
				String msg = "";
				msg = MsgConstat.regCheckMsg.replace("{x}", ",");
				msg = msg.replace("{xxxxxxxxxxxxxxxxxxxxx}","["+code+"]");
				ysServer.sendMsg(ExpSendMsgFuncState.FUNC_SEND_BINDNEW.value, phone, code,msg);
				log.info("手机号："+phone+"，验证码："+code);
				return Result.init("0","验证码已发送");
			}
			
		} catch (Exception e) {
			log.error("发送验证码失败："+e.getMessage());
			return Result.init("1","验证码发送失败！");
		}
	}
	
	/*判断验证码是否正确*/
	@RequestMapping(value = { "/isValidCode.do" })    
	@ResponseBody
	public Result checkCode(HttpServletRequest request, HttpServletResponse response,String phone,String checkCode,
			String funcCode)
	{
		try {
			if(checkCode != null)
			{
				try {
					boolean flag = ysServer.validateMsg(funcCode, phone, checkCode);
					if(flag)
					{
						return Result.init("0", "ok");
					}
					return Result.init("1", "验证码错误");
				} catch (Exception e) {
					return Result.init("1", "验证码错误");
				}
			}else
			{
				return Result.init("1", "验证码错误");
			}
		} catch (Exception e) {
			log.error("校验验证码失败："+e.getMessage());
			return Result.init("1","校验验证码失败！");
		}
	}
	
	public static void main(String[] args) {
		String url = "http://10.211.19.86:4080/branch_tradegate/hessian/ysServer";
		MyHessianProxyFactory factory = new MyHessianProxyFactory();
		factory.setConnectTimeout(600);
		factory.setReadTimeout(100000);
		IYsServer iYsServer = null;
		try {
			iYsServer = (IYsServer) factory.create(IYsServer.class, url, "12345678");
			iYsServer.getMobileMsgCode("13411897029", "5016", "01");
			//System.out.println("发送成功");
			
			iYsServer.checkDynamicCode("9057", "13411897029", "5016", "01");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 进入签收页面
	 * 此处注意，进入此页面的用户可能没有注册，不要紧，我们只需要让其修改签收的标志即可
	 */
	@RequestMapping(value = { "/toExpressReceive.do" })    
	public ModelAndView toExpressReceive(HttpServletRequest request, HttpServletResponse response,String sn) 
	{
		ExpExpressInfo info = expressServer.getExpressInfoBySn(sn);
		request.setAttribute("obj", null);
		if(info == null )
		{
			return toFail(request, "1", "未找到订单信息("+sn+")");
		}
		if(!ExpInfoStatus.SENDING.value.equals(info.getState())
				&& !ExpInfoStatus.SENDED.value.equals(info.getState()) 
				&& !ExpInfoStatus.RECEIVED.value.equals(info.getState())
				)
		{
			return toFail(request, "1", "该状态不能签收("+ExpInfoStatus.getCaption(info.getState())+")");
		}
		request.setAttribute("obj", info);
		request.setAttribute("states", ExpInfoStatus.mVals);
		return new ModelAndView(PATH+"/express/expressReceive");
	}
	
	/*
	 * 签收
	 */
	@RequestMapping(value = { "/expressReceive.do" })
	@ResponseBody
	public Object expressReceive(HttpServletRequest request, HttpServletResponse response,String sn) 
	{
		try {
			//发送给收件的模板消息URL
			ExpWebchatUserinfo wxUser = WxCooikeManager.getWxUser(request);
			Result ret = expressServer.expressInfoReceive(sn, wxUser);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return Result.init("1", "签收失败");
		}
	}
	
}
